
#include "serversocket.h"

ServerSocket::ServerSocket(QObject *parent) :
    QObject(parent)
{
    iServerMode = false;
    iUdpDiscoverySocket = 0;
    QTimer::singleShot(1000,this,SLOT(startNetwork()));
    iWantedToStart = false;
}


void ServerSocket::startNetwork()
{
    iNetworkManager = new QNetworkConfigurationManager(this);
    QNetworkConfiguration cfg = iNetworkManager->defaultConfiguration();
    iNetworkSession = new QNetworkSession(cfg,this);
    iNetworkSession->open();
    iNetworkSession->waitForOpened();
    writeLog("Network open");
    if (iWantedToStart) {
        writeLog("Delayed start");
        start();
    }

}

ServerSocket::~ServerSocket()
{
    stop();
}

void ServerSocket::enableClientMode()
{
    writeLog("CLIENT mode");
    iServerMode = false;
}

void ServerSocket::start()
{
    // http://doc.qt.nokia.com/stable/network-broadcastreceiver-receiver-cpp.html
    // http://doc.qt.nokia.com/stable/network-broadcastsender-sender-cpp.html

    writeLog("Try to start Server");

    if (!iNetworkSession || !iNetworkSession->isOpen()) {
        // Network not open. Open later when network exists at networkUpdated()
        writeLog("Waiting for network...");
        iWantedToStart = true;
        return;
    }

    if (!iUdpDiscoverySocket) {
        iUdpDiscoverySocket = new QUdpSocket(this);
        writeLog("Socket binding...");
        iUdpDiscoverySocket->bind(SERVER_PORT, QUdpSocket::ShareAddress);
        QObject::connect(iUdpDiscoverySocket, SIGNAL(readyRead()),this, SLOT(udpGetData()));
        writeLog("Socket binded");
        //qDebug() << iUdpDiscoverySocket->error();
        //qDebug() << iUdpDiscoverySocket->errorString();
        iWantedToStart = false;
    }
}


void ServerSocket::stop()
{
    if (iUdpDiscoverySocket) {
        iUdpDiscoverySocket->close();
        iUdpDiscoverySocket = 0;
    }

    if (iNetworkSession) {
        iNetworkSession->close();
        iNetworkSession = 0;
    }
}

void ServerSocket::writeLog(QString log)
{
    log = log.prepend("[Udp Client] ");
    //qDebug() << log;
    emit serverLog(log);
}

void ServerSocket::udpGetData()
{
    writeLog("udpGetData()");
    while (iUdpDiscoverySocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(iUdpDiscoverySocket->pendingDatagramSize());
        iUdpDiscoverySocket->readDatagram(datagram.data(), datagram.size());

        if (datagram.startsWith(SERVER_ID)) {
            QString data(datagram);
            QString key(SERVER_ID);
            data = data.mid(data.indexOf((key))+key.length());
            emit kwh(data);
        }
        break;
    }
}

